package com.evan.wj.service;

import com.evan.wj.dao.BookDAO;
import com.evan.wj.pojo.Book;

import com.evan.wj.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.List;

@Service
public class BookService {
    @Autowired
    BookDAO bookDAO;
    @Autowired
    CategoryService categoryService;

    public List<Book> list() {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return bookDAO.findAll(sort);
    }

    public void addOrUpdate(Book book) {
        bookDAO.save(book);
    }

    public void deleteById(int id) {
        bookDAO.deleteById(id);
    }

    public List<Book> listByCategory(int cid) {
        Category category = categoryService.get(cid);
        return bookDAO.findAllByCategory(category);
    }

/*    public List<Book> listByCategoryOrCategory(int cid1, int cid2) {
        Category category1 = categoryService.get(cid1);
        Category category2 = categoryService.get(cid2);
        return bookDAO.findByCategoryOrCategory(category1, category2);
    }*/

    public List<Book> Search(String keywords) {
        return bookDAO.findAllByTitleLikeOrAuthorLike('%' + keywords + '%', '%' + keywords + '%');
    }

    public List<Book> findByScreen(int cid[]){
        List<Book> lb = bookDAO.findAll(new Specification<Book>() {
            public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate p = criteriaBuilder.conjunction().not();
                if (null != cid)
                {
                    Join<Category, Book> join = root.join("category", JoinType.LEFT);
                    for(int a:cid){
                        p = criteriaBuilder.or(p, criteriaBuilder.equal(join.get("id"), a));
                    }
                }
                return p;
            }
        });
        return lb;
    }


}

